﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using RestNews.Models;
using RestNews.Data.Models;

namespace RestNews.Controllers
{
    /// <summary>
    /// Web API controller for viewing user info and editing data
    /// </summary>
    public class UserController : BaseApiController
    {
        /// <summary>
        /// Gets the current User.
        /// </summary>
        /// <returns>User info</returns>
        public HttpResponseMessage Get()
        {
            NewsUser loggedUser = new NewsUser{
                FirstName = CurrentUser.FirstName,
                LastName = CurrentUser.LastName,
                Address = CurrentUser.Address,
                Id = CurrentUser.PersonId,
                Roles = CurrentUser.Roles,
                Username = CurrentUser.Username
            };
            return Request.CreateResponse<NewsUser>(HttpStatusCode.OK, loggedUser);
        }

        /// <summary>
        /// Gets the specified User
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        [Authorize(Roles="Admin")]
        public HttpResponseMessage Get(long id)
        {
            NewsUser selectedUser = NewsUser.GetUser(Db, id);
            if (selectedUser != null)
            {
                return Request.CreateResponse<NewsUser>(HttpStatusCode.OK, selectedUser);
            }
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }

        /// <summary>
        /// Create a new user
        /// </summary>
        /// <param name="newUser">The new user.</param>
        /// <returns></returns>
        [Authorize(Roles="Admin")]
        public HttpResponseMessage Post(NewUserAccount newUser)
        {
            //Test for existing user
            if (Db.Users.FirstOrDefault(u => u.Username == newUser.Username) != null)
            {
                return Request.CreateResponse(HttpStatusCode.Conflict, "An user with this Username already exists.");
            }

            long userId = newUser.CreateUser(Db);
            NewsUser createdUser = new NewsUser
            {
                Id = userId,
                FirstName = newUser.FirstName,
                LastName = newUser.LastName,
                Address = newUser.Address,
                Roles = newUser.Roles,
                Username = newUser.Username
            };

            return Request.CreateResponse(HttpStatusCode.Created, createdUser);
        }
    }
}
